package com.dong.user.controller;

import com.dong.thrift.message.MessageService;
import com.dong.thrift.user.UserInfo;
import com.dong.thrift.user.UserService;
import com.dong.thrift.user.dto.UserDTO;
import com.dong.user.redis.RedisClient;
import com.dong.user.response.LoginResponse;
import com.dong.user.response.ResponseResult;
import com.dong.user.thrift.ServiceProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.thrift.TException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {
    private int sessionTimeout = 1800;
    @Autowired
    private ServiceProvider serviceProvider;
    @Autowired
    private RedisClient redisClient;
    @PostMapping(value="/login")
    @ResponseBody
    public ResponseResult login(@RequestParam("username") String username, @RequestParam("password")String password) {
        //1. 验证用户名密码
        UserService.Client userService = serviceProvider.getUserService();
        UserInfo userInfo = null;
        try {
            userInfo = userService.getUserByName(username);


        } catch (TException e) {
            e.printStackTrace();
            return ResponseResult.USERNAME_PASSWORD_INVALID;
        }
        if(userInfo==null) return ResponseResult.USERNAME_PASSWORD_INVALID;
        //2. 生成token
        if(!userInfo.getPassword().equalsIgnoreCase(md5(password))) {
            return ResponseResult.USERNAME_PASSWORD_INVALID;
        }
        String token = genToken();
        //3. 缓存用户
        redisClient.set(token,UserDTO.toDto(userInfo),sessionTimeout);
    return new LoginResponse(token);
    }
    @GetMapping("/login")
    public String login() {
        return "login";
    }
    @GetMapping("/sendVerifyCode")
    @ResponseBody
    public ResponseResult sendVerifyCode(@RequestParam(value="mobile",required = false)String mobile,
                                         @RequestParam(value = "email",required = false)String email) {
        MessageService.Client messageService = serviceProvider.getMessageService();
        if(StringUtils.isBlank(mobile)&& StringUtils.isBlank(email)) {
            return ResponseResult.EMAIL_OR_MOBILE_REQUIRED;
        }
        String verifyCode = randomCode("0123456789",6);
        boolean isSendSuccess = true;
        if(StringUtils.isNotBlank(mobile)) {
            redisClient.set(mobile,verifyCode,300);
            System.out.println("发送到手机: ["+mobile+"] 验证码: "+verifyCode);
            try {
                messageService.send_sendMobileMessage(mobile,verifyCode);
            } catch (TException e) {
                e.printStackTrace();
                return ResponseResult.MOBILE_NO_ERROR;
            }
        }else{
            redisClient.set(email,verifyCode,300);
         /*   try {
                messageService.sendEmailMessage(email,verifyCode);
            } catch (TException e) {
                log.error("sendVerifyCode-->email:"+email+"-->"+e.getMessage());

            }*/
            System.out.println("发送到邮箱: ["+email+"] 验证码: "+verifyCode);
        }
        if(!isSendSuccess) {
            return ResponseResult.VERIFYCODE_SEND_ERROR;
        }
        return ResponseResult.SEND_VERIFYCODE_SUCCESS;
    }
    @PostMapping("/authentication")
    @ResponseBody
    public UserDTO authentication(@RequestHeader("token")String token) {
        if(StringUtils.isNotBlank(token)) {
            return redisClient.get(token);
        }
        return null;
    }

    @PostMapping("/register")
    @ResponseBody
    public ResponseResult register(@RequestParam("username")String  username,
                                   @RequestParam("password")String password,
                                   @RequestParam(value="email",required = false)String email,
                                   @RequestParam(value="mobile",required = false)String mobile,
                                   @RequestParam(value = "verifyCode")String verifyCode) {
        //1. 验证用户名密码
        UserService.Client userService = serviceProvider.getUserService();
        if(StringUtils.isBlank(email)&& StringUtils.isBlank(mobile)) {
            return ResponseResult.EMAIL_OR_MOBILE_REQUIRED;
        }
        //2. 验证验证码
        if(StringUtils.isBlank(verifyCode)) {
            return ResponseResult.VERIFYCODE_REQUIRED;
        }
        String targetCode=null;
        if(StringUtils.isNotBlank(mobile)) {
             targetCode = redisClient.get(mobile);
        }else {
            targetCode = redisClient.get(email);
        }
        if(!verifyCode.equalsIgnoreCase(targetCode)) {
            return ResponseResult.VERIFYCODE_INVALID;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setEmail(email);
        userInfo.setPassword(md5(password));
        userInfo.setMobile(mobile);
        userInfo.setUsername(username);
        try {
            serviceProvider.getUserService().registerUser(userInfo);
        } catch (TException e) {
            e.printStackTrace();
            return ResponseResult.exception(e);
        }
        return ResponseResult.SUCCESS;
    }



    private String genToken() {
        return  randomCode("0123456789abcdefghijklmnopqrstuvwxyz",32);
    }

    private String randomCode(String sourceStr, int size) {
        StringBuilder builder = new StringBuilder(size);
        Random random = new Random();
        for (int i = 0; i < size; i++) {
            builder.append(sourceStr.charAt(random.nextInt(sourceStr.length())));
        }
        return builder.toString();
    }

    private static String md5(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());

    }

    public static void main(String[] args) {
        String md5 = md5("123456");
        System.out.println(md5);
    }
}
